package com.xqq.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class JsonProcessorService {

    @Value("${json.file-path}")
    private String jsonFilePath;

    private final MqttService mqttService;

    public JsonProcessorService(MqttService mqttService) {
        this.mqttService = mqttService;
    }

    public void processJsonFile() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 1. 首先解析为List<Map>，因为JSON文件是一个数组
            List<Map<String, Object>> rootList = mapper.readValue(
                    new File(jsonFilePath),
                    mapper.getTypeFactory().constructCollectionType(List.class, Map.class)
            );
            // 2. 遍历每个根元素，获取其中的messages数组
            for (Map<String, Object> rootElement : rootList) {
                List<Map<String, Object>> messages = (List<Map<String, Object>>) rootElement.get("messages");
                int messageCount = 0;
                if (messages != null) {
                    for (Map<String, Object> message : messages) {
                        String topic = (String) message.get("topic");
                        String payload = (String) message.get("payload");
//                        String createAt = (String) message.get("createAt");
//                        //解析createAt 时间，如果这个时间是"2025-06-18 17:19:00"之后才进行后续处理，否则直接continue,
//                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
//                        LocalDateTime timeThreshold = LocalDateTime.of(2025, 6, 18, 17, 19, 0);
//                        LocalDateTime messageTime = LocalDateTime.parse(createAt, formatter);
//                        if (messageTime.isBefore(timeThreshold)) {
//                            continue;
//                        }
                        if (messageCount >= 200) {
                            break;
                        }
                        if (topic != null && payload != null) {
                            // 添加test001后缀到topic
                            String modifiedTopic = topic ;

                            // 发送MQTT消息
                            mqttService.publish(modifiedTopic, payload);
                            messageCount++;
                            log.info("Sent => topic: {}, payload: {}", modifiedTopic, payload);

                            // 添加20ms延迟
                            Thread.sleep(1000);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Failed to process JSON file", e);
            throw new RuntimeException("Failed to process JSON file", e);
        }
    }
}
